package cn.yunyichina.scheduler.jobs.service.order.impl;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.BoneService;
import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.bone.BoneDiagnoseVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.scheduler.jobs.service.order.CancleOrderService;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhuxp on 2017/10/25.
 *  为支付订单 超时调度
 * @param
 * @Descrition
 */
@Service
public class CancleOrderServiceImpl implements CancleOrderService {

    private Logger log = LoggerFactory.getLogger(CancleOrderServiceImpl.class);
    @Override
    public void doExecute() {
        OrderExtVo vo =new OrderExtVo();
        vo.setOrderType((short)94);
        vo.setOrderStatus((short)100);
        vo.setEndCreatedTime(beforeNowMin(5));
        vo.setBeginCreatedTime(beforeNowDay(5));
        try {
            log.info("获取取消订单列表, 调用order模块, 入参request=" + JsonUtils.toJsonString(vo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.list", JsonUtils.toJsonString(vo));
            log.info("获取取消订单列表, 调用order模块, 查询结果=" + JsonUtils.toJsonString(orderRespone));
            JSONObject json = JSON.parseObject(orderRespone.getResult());
            JSONArray jsonArray = JSON.parseArray(json.get("datas").toString());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String orderNo = jsonObject.getString("orderNo");
                String doctorId = jsonObject.getString("appointmentDoctorId");
                String consulationTime = jsonObject.getString("scheduleTime");
                Map<String, Object> map = new HashMap<>();
                map.put("order_no", orderNo);
                map.put("order_status", 103);
                Response response = BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(map));
                if ("0".equals(response.getResultCode())) {
                    log.info("取消订单成功!订单号：" + orderNo);
                    //释放号源
                    BoneDiagnoseVo diagnoseVo = new BoneDiagnoseVo();
                    diagnoseVo.setDoctorId(doctorId);
                    diagnoseVo.setConsultationTime(consulationTime);
                    log.info("查询医生放号信息，入参：" + JsonUtils.toJsonString(diagnoseVo));
                    Response resp = BoneService.callHumpFromInternal("yyt.bone.diagnose.list", JsonUtils.toJsonString(diagnoseVo));
                    log.info("查詢醫生放號結果",JsonUtils.toJsonString(resp.getResult()));
                    if ("0".equals(resp.getResultCode())) {
                        JSONObject object = JSON.parseObject(resp.getResult());
                        JSONArray jsonArray1 = JsonUtils.parseArray(object.get("list").toString());
                        if(!jsonArray1.isEmpty()) {
                            BoneDiagnoseVo boneDiagnoseVo = JsonUtils.parseObject(jsonArray1.get(0), BoneDiagnoseVo.class);
                            if (boneDiagnoseVo.getSubscribeNum() > 0) {
                                boneDiagnoseVo.setSubscribeNum(boneDiagnoseVo.getSubscribeNum() - 1);
                                log.info("更新医生放号信息，入参：" + JsonUtils.toJsonString(boneDiagnoseVo));
                                Response returnResp = BoneService.callHumpFromInternal("yyt.bone.diagnose.update", JsonUtils.toJsonString(boneDiagnoseVo));
                                if ("0".equals(returnResp.getResultCode())) {
                                    log.info("更新医生放号信息成功");
                                }
                            }
                        }
                    }
                } else {
                    log.error("取消订单号失败!" + response.getResultMessage());
                }
            }
        }else {
                log.info("未查询到需要取消的面诊订单!此次任务执行完成！"+new Date());
            }
        }catch (Exception e){
            log.error("取消订单定时调度任务 异常",e);
        }
    }

    private String beforeNowMin(int i) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间前5分钟 时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -i);
        Date now = calendar.getTime();
        String returnTime = simpleDateFormat.format(now);
        return returnTime;
    }
    private String beforeNowDay(int i) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间前5天 时间戳
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -i);
        date = calendar.getTime();
        return simpleDateFormat.format(date);
    }
}
